package com.star.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.star.exception.ServiceException;
import com.star.exception.SystemException;
import com.star.pojo.SecurityUser;
import com.star.pojo.User;
import com.star.result.API;
import com.star.security.TokenManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 认证过滤器
 *
 * @author tanyapeng
 * @date 2021/3/7
 */
@Slf4j
public class TokenLoginFilter extends UsernamePasswordAuthenticationFilter {

    private TokenManager tokenManager;

    private StringRedisTemplate stringRedisTemplate;

    private AuthenticationManager authenticationManager;

    public TokenLoginFilter(AuthenticationManager authenticationManager, TokenManager tokenManager, StringRedisTemplate stringRedisTemplate) {
        this.authenticationManager = authenticationManager;
        this.tokenManager = tokenManager;
        this.stringRedisTemplate = stringRedisTemplate;
        this.setPostOnly(false);
        this.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/admin/login", "POST"));
    }

    /**
     * 1 获取表单提交用户名和密码
     *
     * @param request
     * @param response
     * @return
     * @throws AuthenticationException
     */
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException {
        // 获取表单提交数据
        try {
            User user = new ObjectMapper().readValue(request.getInputStream(), User.class);
            if (user.getUsername() == null) {
                throw new ServiceException(20001, "用户名不能为空!");
            }
            if (user.getPassword() == null) {
                throw new ServiceException(20001, "密码不能为空!");
            }
            log.info("用户名和密码，{},{}", user.getUsername(), user.getPassword());
            return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword(),
                    new ArrayList<>()));
        } catch (ServiceException e) {
            throw e;
        } catch (Exception e) {
            log.error("Authentication error - {},{}", ExceptionUtils.getStackTrace(e), request, response);
            throw new SystemException(10001, "获取表单提交用户名和密码出错");
        }
    }

    /**
     * 2 认证成功调用的方法
     *
     * @param request
     * @param response
     * @param chain
     * @param authResult
     * @throws IOException
     * @throws ServletException
     */
    @Override
    protected void successfulAuthentication(HttpServletRequest request,
                                            HttpServletResponse response,
                                            FilterChain chain,
                                            Authentication authResult) {
        try {
            // 认证成功，得到认证成功之后用户信息
            SecurityUser user = (SecurityUser) authResult.getPrincipal();
            // 根据用户名生成token
            String token = tokenManager.createToken(user.getCurrentUserInfo().getUsername());
            // 把用户名称和用户权限列表放到redis
            addToken(user.getCurrentUserInfo().getUsername(), user.getPermissionValueList());
            // 返回token
            ObjectMapper mapper = new ObjectMapper();
            Map<String, Object> map = new HashMap<>();
            map.put("token", token);
            mapper.writeValue(response.getWriter(), API.ok(map));
        } catch (ServiceException e) {
            throw e;
        } catch (Exception e) {
            log.error("successfulAuthentication error - {},{}", ExceptionUtils.getStackTrace(e), request, response);
            throw new SystemException(10001, "认证出错");
        }
    }

    /**
     * 3 认证失败调用的方法
     *
     * @param request
     * @param response
     * @param failed
     * @throws IOException
     * @throws ServletException
     */
    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request,
                                              HttpServletResponse response,
                                              AuthenticationException failed) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.writeValue(response.getWriter(), API.error(HttpStatus.PROXY_AUTHENTICATION_REQUIRED.value(), "(认证失败) 请重新认证!"));
        } catch (Exception e) {
            log.error("unsuccessfulAuthentication error - {},{},{}", ExceptionUtils.getStackTrace(e), request, response, failed);
            throw new SystemException(10002, "认证失败");
        }
    }

    /**
     * 在redis里添加用户名称和用户权限列表
     *
     * @param username
     * @param permissionValueList
     */
    private void addToken(String username, List<String> permissionValueList) {
        try {
            stringRedisTemplate.opsForList().rightPushAll(username, permissionValueList);
        } catch (Exception e) {
            log.error("addToken error - {},{},{}", ExceptionUtils.getStackTrace(e), username);
            throw new SystemException(10002, "添加token出错");
        }
    }
}
